package com.yupi.yuaiagent.demo.invoke.invoke;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.yupi.yuaiagent.demo.invoke.TestApiKey;

/**
 * HTTP 调用 ai
 */
public class HttpAiInvoke {
    public static void main(String[] args) {
        // 构建请求URL
        String url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

        // 构建请求头
        String apiKey = System.getenv(TestApiKey.API_KEY); // 从环境变量获取API密钥
        if (apiKey == null) {
            apiKey = TestApiKey.API_KEY; // 或者直接硬编码（不推荐生产环境使用）
        }

        // 构建请求体JSON
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "qwen-plus");

        // 构建messages数组
        JSONArray messages = new JSONArray();

        // 添加system消息
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", "You are a helpful assistant.");
        messages.add(systemMessage);

        // 添加user消息
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", "你是谁？");
        messages.add(userMessage);

        // 构建input对象
        JSONObject input = new JSONObject();
        input.put("messages", messages);
        requestBody.put("input", input);

        // 构建parameters对象
        JSONObject parameters = new JSONObject();
        parameters.put("result_format", "message");
        requestBody.put("parameters", parameters);

        // 发送HTTP请求
        HttpResponse response = HttpRequest.post(url)
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute();

        // 处理响应
        if (response.isOk()) {
            System.out.println("请求成功：");
            System.out.println(response.body());
        } else {
            System.out.println("请求失败：");
            System.out.println("状态码：" + response.getStatus());
            System.out.println("响应内容：" + response.body());
        }
    }
}